import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * @author weizhuowu
 *
 */
public class AliveMsg extends Message{
    String aliveUserKey;
	InetAddress aliveIpAddress;
	int alivePortNum;
	String aliveUserName;
	boolean isLeader;
	
	AliveMsg(UDPClient client){
		super("IP:"+client.getLocalIpAddress()+":PORT:"+client.getLocalPortNum()+":NAME:"+client.getUserName());
		this.aliveUserKey = "IP:"+client.getLocalIpAddress()+":PORT:"+client.getLocalPortNum();
		try {
			this.aliveIpAddress = InetAddress.getByName((client.getLocalIpAddress()));
		} catch (UnknownHostException e) {
			System.out.println("Sorry, Hostname/IpAddress is not a valid hostName/IPAddress");
			e.printStackTrace();
		}
		this.alivePortNum = client.getLocalPortNum();
		this.aliveUserName = client.getUserName();
		this.isLeader = false;
	}
	
	AliveMsg(String content){
		super(content);
		/*Analyze aliveMsg, get clientInfo*/
		this.aliveUserKey = content.split(":NAME:")[0];//memberList key
		String[] msgArray = content.split(":");
		/*["IP", "172.19.39.107", "PORT", "3333", "NAME", "weizhuo", "ISLEADER", "true/false"]*/		
		try {
			this.aliveIpAddress = InetAddress.getByName(msgArray[1]);
		} catch (UnknownHostException e) {
			System.out.println("Sorry, Hostname/IpAddress in aliveMsg is not a valid hostName/IPAddress");
			e.printStackTrace();
		}//InetAddress
		String portNum = msgArray[3].trim();
		this.alivePortNum = Integer.parseInt(portNum);//portNum
		this.aliveUserName = msgArray[5];//userName			
		if(content.contains("ISLEADER")){
			this.isLeader = Boolean.valueOf(msgArray[7]);
		}
	}
	
	public String getAliveUserKey(){
		return this.aliveUserKey;
	}
	
	public InetAddress getAliveIpAddress(){
		return this.aliveIpAddress;
	}
	
	public int getAlivePortNum(){
		return this.alivePortNum;
	}
	
	public String getAliveUserName(){
		return this.aliveUserName;
	}
	
	public boolean isAliveLeader(){
		return this.isLeader;
	}
}
